﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace Core.Helper
{
    public sealed class Enum
    {
        /// <summary>
        /// 获取枚举类型的所有项，返回集合
        /// </summary>
        /// <param name="type">枚举类型</param>
        /// <returns>返回System.ValueTuple集合类型，item1为枚举int值，item2为枚举name，item3为描述</returns>
        public static List<Tuple<int, string, string>> Tuples(Type type)
        {
            List<Tuple<int, string, string>> list = new List<Tuple<int, string, string>>();
            FieldInfo[] items = type.GetFields();
            foreach (FieldInfo item in items)
            {
                string description = string.Empty;
                object[] objects = item.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objects != null)
                {
                    DescriptionAttribute[] attributes = objects as DescriptionAttribute[];
                    description = attributes[0].Description;
                }
                string name = item.Name;
                int value = (int)System.Enum.Parse(type, name);
                list.Add(new Tuple<int, string, string>(value, name, description));
            }

            return list;
        }

        public static List<EnumModel> List(Type type)
        {
            List<Tuple<int, string, string>> tuples = Tuples(type);
            List<EnumModel> result = new List<EnumModel>();
            if (tuples.Any())
            {
                foreach (Tuple<int, string, string> item in tuples)
                {
                    result.Add(new EnumModel { Value = item.Item1, Name = item.Item2, Description = item.Item3 });
                }
            }

            return result;
        }
    }
}